import React, { useEffect, useRef, useState, useMemo } from 'react'
import { Chart } from '@antv/g2'
import styles from './LineChart.module.less'

const LineChart = (props) => {
	const { id } = props
	const chartRef = useRef()
	const data = [
		{ label: 'Mon.', value: 7 },
		{ label: 'Tues.', value: 13 },
		{ label: 'Wed.', value: 3 },
		{ label: 'Thur1.', value: 0 },
		{ label: 'Thur2.', value: 1 },
		{ label: 'Thur3.', value: 2 },
		{ label: 'Thur4.', value: 3 },
	]

	const [chart, setChart] = useState(null)
	const [maxHeight, setMaxHeight] = useState(null)
	const [init, setInit] = useState(false)

	const dataValues = data.map((item) => item.value)
	const max = Math.max(...dataValues)

	useEffect(() => {
		if (data && !chart) {
			const maxH = data.length * 30 > 200 ? data.length * 30 : 200
			setMaxHeight(maxH)
			const chart = new Chart({
				container: `${id}line`,
				width: 200,
				height: maxH,
			})
			setChart(chart)
		}
	}, [data])

	const renderChart = () => {
		chart.clear()
		chart.data(data)

		const margin = 1 / 6

		chart.axis('value', {
			label: null,
			grid: null,
		})

		chart.axis('label', {
			label: {
				offset: 12,
			},
			tickLine: {
				alignTick: false,
			},
		})

		chart.scale('value', {
			range: [0, 1 - margin / 2],
			min: 0,
			max: max + 2,
		})

		chart.coordinate().transpose()

		chart.tooltip({
			showMarkers: false,
			showTitle: false,
		})

		chart.interaction('active-region')

		chart.legend(false)

		chart
			.interval()
			.position('label*value')
			// .color('value', (value) => "#027db4")
			.color('#027db4')
			.label('value', (value) => {
				return {
					content: (data) => {
						if (value) {
							return value + 'h'
						}
					},
					offsetX: -6,
				}
			})
			.tooltip('label*value', (label, value) => {
				return {
					name: label,
					value: value,
				}
			})
			.size(16)

		chart.render()
	}

	useEffect(() => {
		if (chart && !init) {
			renderChart()
			setInit(true)
		}
	}, [chart, init])

	return (
		<div className={styles.lineChartBox}>
			<div id={`${id}line`} ref={chartRef} style={{ height: maxHeight }} />
		</div>
	)
}

export default LineChart
